package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xrit.sunnyday.dao.SetMealDao;
import com.xrit.sunnyday.entity.QueryPageBean;
import com.xrit.sunnyday.exception.SunnydayException;
import com.xrit.sunnyday.pojo.Setmeal;
import com.xrit.sunnyday.service.SetMealService;
import com.xrit.sunnyday.utils.QiNiuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名称: SetMealServiceImpl
 * 类描述:TODO
 * 创建人: czb
 * 创建时间:2022/6/13 下午 04:30
 * Version 1.0.0
 */
@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    @Value("${out_put_path}")
    private String out_put_path;

    @Override
    public PageInfo<Setmeal> findPage(QueryPageBean queryPageBean) {
//        开启分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
            queryPageBean.setQueryString("%" + queryPageBean.getQueryString() + "%");
        }
        List<Setmeal> list = setMealDao.findPage(queryPageBean.getQueryString());
        PageInfo<Setmeal> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /*删除套餐*/
    @Override
    public void deleteById(Integer id) throws SunnydayException {
        /*先查询订单有没有套餐*/
        int i = setMealDao.findByOrder(id);
        if (i > 0) {
            throw new SunnydayException("您的套餐已经绑定了订单");
        }
        setMealDao.deleteSetMealAndCheckGroup(id);
        setMealDao.deleteById(id);
    }

    /*添加套餐*/
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.add(setmeal);
        Integer setMealID = setmeal.getId();
        if (null != checkgroupIds && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                setMealDao.addSetMealCheckGroup(setMealID, checkgroupId);
            }
        }
//        freemarker处理
        generatMobileStaticHtml();
    }

    private void generatMobileStaticHtml() {
        try {
            //生成套餐列表页面
            generateSetMealListHtml();
            //生成套餐详情页面
            generateSetMealDetailHtml();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * @description: 生成页面详情
     * @param:
     * @return: void
     * @author czb20
     * @date:  下午 12:22
     */

    private void generateSetMealDetailHtml() {
        String templateName = "mobile_setmeal_detail.ftl";
        //查询所有的套餐
        List<Setmeal> all = setMealDao.findAll();
        //给图片加上域名
        for (Setmeal setmeal : all) {
            Setmeal setMealDetail = setMealDao.findDetailById(setmeal.getId());
            setMealDetail.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal",setMealDetail);
            String setmealListFile = out_put_path+"mobile_setmeal_" + setMealDetail.getId() + ".html";
            generateHtml(templateName,map,setmealListFile);
        }


    }
    /**
     * @description: 生成套餐列表
     * @param:
     * @return: void
     * @author czb20
     * @date:  下午 12:21
     */

    private void generateSetMealListHtml() {
        String templateName = "mobile_setmeal.ftl";
        //查询所有的套餐
        List<Setmeal> all = setMealDao.findAll();
        //给图片加上域名
        all.forEach(setmeal -> {setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());});
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList",all);
        //4.输出全路径
        String setmealListFile = out_put_path+"mobile_setmeal.html";
        generateHtml(templateName,map,setmealListFile);

    }


    /**
     * @description: 生成静态页面的方法
     * @param: templateName 模板名
    dataMap 生成静态页面需要的数据
    outFileName 文件名
     * @return: void
     * @author czb20
     * @date:  下午 12:15
     */

    public void generateHtml(String templateName, Map<String, Object> dataMap, String outFileName) {
        Configuration configuration = freeMarkerConfig.getConfiguration();
        BufferedWriter writer = null;
        try {
            Template template = configuration.getTemplate(templateName);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFileName), "UTF-8"));
            template.process(dataMap,writer);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                assert writer != null;
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setMealDao.findById(id);
        setmeal.setImg(QiNiuUtils.DOMAIN + setmeal.getImg());
        return setmeal;
    }

    @Override
    public Integer[] findSetMealAndCheckGroup(Integer id) {
        List<Setmeal> setmeal = setMealDao.findSetMealAndCheckGroup(id);
        Integer[] integers = new Integer[setmeal.size()];
        for (int i = 0; i < setmeal.size(); i++) {
            integers[i] = setmeal.get(i).getId();
        }
        return integers;
    }

    @Override
    public void update(Setmeal setmeal, Integer[] checkgroupIds) {
//        先修改套餐
        setMealDao.update(setmeal);
//       再改修中间表 先删除再添加
        Integer setMealId = setmeal.getId();
        if (null != checkgroupIds && checkgroupIds.length > 0) {
            setMealDao.deleteSetMealAndCheckGroup(setmeal.getId());
            for (Integer checkgroupId : checkgroupIds) {
                setMealDao.addSetMealCheckGroup(setMealId, checkgroupId);
            }
        }

    }

    @Override
    public List<String> findImgs() {
        return setMealDao.findImgs();
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public Setmeal findDetailById(int id) {
        return setMealDao.findDetailById(id);
    }

    @Override
    public List<Map<String, Object>> getSetmealReport() {
        return setMealDao.getSetmealReport();
    }
}
